package com.rest.demo.concurrent;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Administrator
 * @decription
 * @Date 2018-02-01 15:05
 */
public class Buffer {
    final Lock lock = new ReentrantLock();

    final Condition notFull = lock.newCondition();

    final Condition notEmpty = lock.newCondition();

    final Object[] items = new Object[10];

    int putptr,takeptr,count;

    public void put(Object x) throws InterruptedException {
        lock.lock();
        try {
            while(count == items.length) {
                System.out.println(Thread.currentThread().getName()+" 空间不足，暂时无法存数据");
                notFull.await();
            }
            items[putptr] = x;
            if(++putptr == items.length) {
                putptr = 0;
            }
            count++;
            System.out.println(Thread.currentThread().getName()+" 将值已存入,值:" + x);
            notEmpty.signal();
        } finally {
            lock.unlock();
        }
    }

    public Object take() throws InterruptedException {
        lock.lock();
        try {
            while (count == 0) {
                System.out.println(Thread.currentThread().getName()+" 空间中暂无数据，请等待");
                notEmpty.await();
            }
            Object x = items[takeptr];
            if(++takeptr == items.length) {
                takeptr = 0;
            }
            count --;
            System.out.println(Thread.currentThread().getName()+" 取出了数据,值:" + x);
            notFull.signal();
            return x;
        } finally {
            lock.unlock();
        }
    }
}
